package org.jeecg.common.util.sm.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.legacy.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.security.Security;

public class SM4Encryption {

    static {
        // 添加BouncyCastle作为安全提供者
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws Exception {
//        String inputFilePath = "D://opt/a.txt";
//        String inputFilePath2 = "D://opt/a2.txt";
//        String outputFilePath = "D://opt/a1.txt.enc";

        String inputFilePath = "D://test/projectM.json.enc";
        String inputFilePath2 = "D://test/projectM.json";
        String outputFilePath = "D://test/projectM.json.enc";

//        String inputFilePath = "D://opt/test.pdf";
//        String inputFilePath2 = "D://opt/test2.pdf";
//        String outputFilePath = "D://opt/test.pdf.enc";

//        String inputFilePath = "D://opt/project.json";
//        String inputFilePath2 = "D://opt/project2.json";
//        String outputFilePath = "D://opt/project.json.enc";
        byte[] keyBytes = new byte[16]; // 16字节密钥
        byte[] keyDatatmp = ByteUtils.fromHexString("60561ACB342805CF");
        // 初始化密钥（这里仅为示例，实际应用中应确保密钥的安全性）
        new SecureRandom().nextBytes(keyBytes);



//        encryptFile(inputFilePath, outputFilePath, "60561ACB342805CF".getBytes());


        decryptFile(outputFilePath,inputFilePath2, "60561ACB342805CF".getBytes());
    }



    public static void encryptFile(String inputFile, String outputFile, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "BC");
        SecretKeySpec secretKey = new SecretKeySpec(key, "SM4");

        // 初始化Cipher为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 读取文件内容
        byte[] fileContent = Files.readAllBytes(Paths.get(inputFile));

        // 加密数据
        byte[] encryptedData = cipher.doFinal(fileContent);

        // 将加密后的数据写入输出文件
        Files.write(Paths.get(outputFile), encryptedData);
    }

    public static void decryptFile(String inputFile, String outputFile, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS7Padding", "BC");
        SecretKeySpec secretKey = new SecretKeySpec(key, "SM4");

        // 初始化Cipher为解密模式
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 读取加密文件内容
        byte[] encryptedData = Files.readAllBytes(Paths.get(inputFile));

        // 解密数据
        byte[] decryptedData = cipher.doFinal(encryptedData);

        // 将解密后的数据写入输出文件
        Files.write(Paths.get(outputFile), decryptedData);
    }
}